<template>
  <div class="login-container">
    <video autoplay muted loop @contextmenu="contextmenu" class="background-video">
      <source src="@/assets/images/bg.mp4" type="video/mp4" />
      Your browser does not support the video tag.
    </video>
    <div class="login_main">
      <div class="login_logo">
        <img src="@/assets/images/logo-33px.png" alt="" />
        <div>智慧用电管控平台</div>
      </div>
      <div class="login_subtitle">
        <div class="login_line"></div>
        <div class="login_text">登录您的平台账号</div>
      </div>
      <div class="login_form">
        <el-form ref="ruleFormRef" :model="ruleForm" :rules="loginRules" size="large">
          <el-form-item prop="username">
            <el-input v-model="ruleForm.username" clearable placeholder="请输入帐号" style="width: 420px;" />
          </el-form-item>
          <el-form-item prop="password">
            <el-input v-model="ruleForm.password" clearable show-password placeholder="请输入密码" style="width: 420px;" />
          </el-form-item>
          <el-form-item>
            <div class="login_remember">
              <el-checkbox v-model="checked">
                <span class="flex">记住密码</span>
              </el-checkbox>
            </div>
          </el-form-item>
          <el-form-item>
            <el-button class="login_btn" size="default" type="primary" :loading="loading" @click="onLogin(ruleFormRef)">
              登录
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <div class="login_bot">
      <div>© 版权所有2024 ABB</div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onBeforeUnmount, watch } from "vue";
import { useRouter } from "vue-router";
import { ElForm, ElInput, ElFormItem, ElCheckbox, ElButton, ElMessage } from "element-plus";
import Cookies from 'js-cookie'
import dayjs from 'dayjs'
import { getLogin } from '@/api/screen.js';
import { setToken } from '@/utils/auth.js';

const router = useRouter();

const loading = ref(false);
const checked = ref(false);
const ruleForm = reactive({
  username: "admin",
  password: "admin123"
});
const ruleFormRef = ref(null);

let loginRules = {
  username: [
    { required: true, message: "请输入帐号", trigger: "blur" },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
  ]
}

const onLogin = async (formEl) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      loading.value = true;
      getLogin({ username: ruleForm.username, password: ruleForm.password })
        .then(res => {
          console.log('res:', res)
          let timeout = dayjs(res.tokenTimeout).diff(dayjs(), 'day')
          timeout = timeout > 0 ? timeout : 30
          console.log('timeout:', timeout)
          if (checked.value) {
            Cookies.set('username', ruleForm.username, { expires: 30 })
            Cookies.set('password', ruleForm.password, { expires: 30 })
            Cookies.set('rememberMe', true, { expires: 30 })
          } else {
            Cookies.remove('username')
            Cookies.remove('password')
            Cookies.remove('rememberMe')
          }
          setToken(res.token);
          ElMessage.success("登录成功!");
          router.push("/");
        }).catch(err => {
          console.log('err:', err)
          ElMessage.error(res.message);
        }).finally(() => (loading.value = false));
    }
  });
};

const getCookie = () => {
  const username = Cookies.get('username')
  const password = Cookies.get('password')
  const rememberMe = Cookies.get('rememberMe')

  ruleForm.username = username === undefined ? ruleForm.username : username,
  ruleForm.password = password === undefined ? ruleForm.password : password
  checked.value = rememberMe === undefined ? false : true
}

/** 使用公共函数，避免`removeEventListener`失效 */
function onkeypress({ code }) {
  if (["Enter", "NumpadEnter"].includes(code)) {
    onLogin(ruleFormRef.value);
  }
}

onMounted(() => {
  getCookie()
  window.document.addEventListener("keypress", onkeypress);

  const video = document.querySelector("video");
  video.addEventListener('click', (event) => {
    event.preventDefault();
  })
});

onBeforeUnmount(() => {
  window.document.removeEventListener("keypress", onkeypress);
});

//禁止右键行为
const contextmenu = (e) => {
  e.returnValue = false
}
</script>

<style scoped lang="scss">
.login-container {
  width: 100vw;
  height: 100vh;
  overflow: hidden;
  background-color: #fff;

  .background-video {
    width: 100%;
    height: 100%;
    object-fit: cover;
    opacity: 0.2;
  }

  .login_main {
    position: fixed;
    top: 50%;
    left: 50%;
    z-index: 1;
    transform: translate(-50%, -50%);
    // width: 37%;
    background: rgba($color: #fff, $alpha: 0.5);
    box-shadow: 3px 0px 21px 0px rgba($color: #000000, $alpha: 0.2);
    border-radius: 5px 5px 5px 5px;
    padding: 122px 120px;

    .login_logo {
      display: flex;
      align-items: center;
      font-size: 36px;
      font-weight: bold;
      color: #000;

      img {
        margin-right: 20px;
      }
    }

    .login_subtitle {
      margin-top: 90px;

      .login_line {
        width: 47px;
        height: 4px;
        background-color: var(--main-color);
      }

      .login_text {
        font-size: 24px;
        line-height: 24px;
        color: #333;
        padding-top: 20px;
      }
    }

    .login_form {
      padding-top: 60px;

      .login_btn {
        margin-top: 20px;
        width: 100%;
        height: 47px;
      }
    }
  }

  .login_bot {
    position: fixed;
    bottom: 36px;
    width: 100%;
    text-align: center;
  }
}
</style>
